package com.lq.nine;

/**
 * @author lq
 * @date 2020-09-21 12:56
 */
public class swapPairs24 {

    /**
     * 给定一个链表，两两交换其中相邻的节点，并返回交换后的链表。
     *
     * 你不能只是单纯的改变节点内部的值，而是需要实际的进行节点交换。
     *
     *  
     *
     * 示例:
     *
     * 给定 1->2->3->4, 你应该返回 2->1->4->3.
     * @param args
     */
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        ListNode r = swapPairs(l1);
        while (r != null) {
            System.out.println(r.val);
            r = r.next;
        }
    }

    public static ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newTop = head.next;
        ListNode two = head;
        two.next = swapPairs(newTop.next);
        newTop.next = two;
        return newTop;
    }

    // 迭代
    public static ListNode swapPairs2(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode preNode = dummy;
        while (head != null && head.next != null) {
            ListNode first = head;
            ListNode second = head.next;
            preNode.next = second;
            first.next = second.next;
            second.next = first;
            preNode = first;
            head = first.next;
        }
        return dummy.next;
    }
}
